#include "Log.h"
#include <spdlog/sinks/stdout_color_sinks.h>

#include <vector>

using std::vector;

shared_ptr<spdlog::logger> Log::_logger = nullptr;
Log &Log::getInstance()
{
    static Log instance;
    return instance;
}

void Log::init(const string &path, size_t queSize = 8192, int threadnum = 1, size_t maxFileSize = 1024, size_t maxFiles = 2)
{
    spdlog::init_thread_pool(queSize, threadnum);
    // create->回滚文件sink
    auto rotating_sink = std::make_shared<spdlog::sinks::rotating_file_sink_mt>(path, maxFileSize, maxFiles);
    rotating_sink->set_pattern("[%Y-%m-%d %T.%e][%l][t:%t][%s:%#] %v");
    // 创建控制台sink（带颜色输出）
    auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
    console_sink->set_pattern("[%Y-%m-%d %T.%e][%^%l%$] %v");

    //create->异步logger
    vector<spdlog::sink_ptr> sinks{rotating_sink, console_sink};
    _logger = std::make_shared<spdlog::async_logger>(
        "async_logger",
        sinks.begin(), sinks.end(),
        spdlog::thread_pool(),
        spdlog::async_overflow_policy::block
    );


    // 格式
    // _logger->set_pattern("[%Y-%m-%d %H:%M:%S.%e] [%l] [%t] %v");
    // 设置刷新级别
    _logger->flush_on(spdlog::level::warn);
    // 注册全局logger
    spdlog::register_logger(_logger);
    spdlog::set_default_logger(_logger);

    // 设置级别
    spdlog::set_level(spdlog::level::trace);
}

void Log::shutdown()
{
    spdlog::shutdown();
}